﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace Ymatou.ServiceCenter.Common
{
    /// <summary>
    /// 工具类
    /// </summary>
    public static class Utils
    {
        /// <summary>
        /// 检测IP地址规则的正则表达式
        /// </summary>
        private const string Pattern =
            @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$";

        //MD5加密程序（32位小写）
        public static string ToMd5(string value)
        {
            byte[] result = Encoding.Default.GetBytes(value);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            string md = BitConverter.ToString(output).Replace("-", "");
            return md.ToLower();
        }

        private static string _localIp = null;
        private static string GetLocalIp()   //获取本地IP 
        {
            if (_localIp != null) return _localIp;
            IPAddress[] ipAddrs = Dns.GetHostAddresses(Dns.GetHostName());
            string ip = string.Empty;
            foreach (IPAddress ipAddr in ipAddrs)
            {
                ip = ipAddr.ToString();
                if (IsIp(ip))
                    break;
            }
            _localIp = ip;
            return _localIp;

        }

        /// <summary>
        /// 本机IP
        /// </summary>
        public static string LocalIp
        {
            get { return _localIp ?? (_localIp = GetLocalIp()); }
        }

        /// <summary>
        /// 中英文字符串截取
        /// </summary>
        /// <param name="input">原字符串</param>
        /// <param name="length">截取的长度</param>
        /// <returns>截取后的字符串</returns>
        public static string Intercept(string input, int length)
        {
            Encoding encode = Encoding.GetEncoding("gb2312");
            byte[] bytes = encode.GetBytes(input);
            if (bytes.Length <= length) return input;
            int m = 0, n = 0;
            foreach (byte b in bytes)
            {
                if (n >= length) break;
                if (b > 127) m++; //重要一步：对前length个字节中的值大于127的字符进行统计
                n++;
            }
            if (m % 2 != 0) n = length - 1; //如果非偶：则说明末尾为双字节字符，截取位数减1
            return encode.GetString(bytes, 0, n);
        }

        /// <summary>
        /// IP地址验证的正则表达式
        /// </summary>
        private static readonly Regex PatternRegex = new Regex(Pattern);

        public static bool IsIp(string ip)
        {
            return !string.IsNullOrWhiteSpace(ip) && PatternRegex.IsMatch(ip.Trim());
        }
    }
}
